<?php

namespace App\Http\Controllers;

use App\Facades\AjaxResponse;
use App\Model\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller{

	/**
	 * 添加/注册 用户
	 *
	 * @param Request $request
	 * @return mixed
	 */
    public function index(Request $request){
		$validator = Validator::make($request->all(), [
			'email' 	=> 'required|email',
			'user_name'	=> 'required|string',
			'password' 	=> 'required|string',
		]);
		if($validator->fails()){
			return AjaxResponse::fail(AJAX_CODE_REQUEST_PARAMS_ERROR, $validator->errors()->first());
		}
		$request['email'] = $request->input('email');
		$request['user_name'] = $request->input('user_name');
		$request['password'] = $request->input('password');

		//验证邮箱是否已被注册
		$conditions['where'][User::FIELD_EMAIL] = $request['email'];
		$user = User::getUserCountByConditions($conditions);
		if($user){
			return AjaxResponse::fail(AJAX_CODE_EMAIL_REPEAT_ERROR);
		}
		$salt_word = User::setSalt();
		$insert_data = [
			User::FIELD_EMAIL => $request['email'],
			User::FIELD_USER_NAME => $request['user_name'],
			User::FIELD_SALT_WORD => $salt_word,
			User::FIELD_PASSWORD =>  User::encryptPassword($request['password'], $salt_word),
		];
		if(User::add($insert_data)){
			$params = '?token='.time().'&email='.$request['email'];
			$send_data = [
				'link' => $_SERVER["HTTP_HOST"].'/api/activeEmail'.$params,
				'title' => '邮箱激活',
				'user_name' => $request['user_name'],
			];
			if($this->sendMail($request['email'], $send_data, $subject = '邮箱激活')){
				return AjaxResponse::success();
			}
			return AjaxResponse::fail(AJAX_CODE_REGISTER_FAIL);
		}else{
			return AjaxResponse::fail(AJAX_CODE_REGISTER_FAIL);
		}
    }

	/**
	 * 邮箱激活
	 *
	 * @param Request $request
	 * @return \AjaxResponse
	 */
    public function activeEmail(Request $request){
    	$request['email'] = $request->input('email');
		$update_data = [
			User::FIELD_EMAIL_STATUS => User::ENABLE_EMAIL_STATUS
		];
		$conditions['where'][User::FIELD_EMAIL] = $request['email'];
		$result = User::updateUserByConditions($update_data, $conditions);
		if($result){
			return AjaxResponse::success();
		}
		return AjaxResponse::fail();
	}
}
